Java 读书笔记 21.1并发

并发

终于来到这里了,好开心;

线程定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Liftoff implements Runnable{ //接口
@Override
public void run() { //实现run方法
}
}
public static void main(String []arg){
//第一种
Liftoff liftoff = new Liftoff();
liftoff.run();
//第二种
Thread thread = new Thread(new Liftoff());
thread.start();
}
}

Executor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainThread {
public static void main(String []arg)
{
//ExecutorService executorService = Executors.newCachedThreadPool(); // 每一个任务都创建新的线程
ExecutorService executorService = Executors.newFixedThreadPool(2); //同时只允许两个线程工作;
for (int i1 = 0; i1 < i; i1++) {
//new Thread(new Liftoff()).start();
executorService.execute(new Liftoff());
}
executorService.shutdown();
System.out.println("wait");
}
}

Callable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class TaskWithResult implements Callable<String> {
public static void main(String []arg)
{
ExecutorService executorService = Executors.newCachedThreadPool();
ArrayList<Future<String>> futures = new ArrayList<>();
for (int i = 0;i<10;i++)
{
futures.add(executorService.submit(new TaskWithResult(i)));
}
for (Future<String> fs : futures)
{
try {
System.out.println(fs.get());
}catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
private int id;
public TaskWithResult(int id)
{
this.id= id;
}
@Override
public String call() throws Exception { //实现call方法,用以返回值;
return "result "+id;
}
}

优先级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Priority implements Runnable{
public static void main(String []arg)
{
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i=0;i<5;i++)
{
executorService.execute(new Priority(Thread.MIN_PRIORITY));
}
executorService.execute(new Priority(Thread.MAX_PRIORITY));
executorService.shutdown();
}
private volatile double d;
private int priority;
private int countdown;
public Priority(int priority)
{
this.priority = priority;
}
public String toString()
{
return Thread.currentThread() + " :"+countdown;
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
while (true) {
for (int i = 1; i < 100000; i++) {
d += (Math.PI + Math.E) / (double) i;
if (i % 1000 == 0)
Thread.yield();
}
System.out.println(this);
if (--countdown == 0)
return;
}
}
}
//输出会发现优先级高的线程执行次数远多于一般线程

后台线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class SimpleDaemons implements Runnable {
@Override
public void run() {
try {
while (true)
{
TimeUnit.MILLISECONDS.sleep(500);
System.out.println(Thread.currentThread()+""+this);
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt");
}
finally {
System.out.println("finally"); //Main函数退出,后台直接跳出,finally不执行嘞
}
}
public static void main(String []arg) throws InterruptedException {
for (int i=0;i<10;i++)
{
Thread deamon = new Thread(new SimpleDaemons());
deamon.setDaemon(true);
deamon.start();
}
System.out.println("all daemon started");
TimeUnit.SECONDS.sleep(5); //如果主线程不睡,就直接停止了,后台自动停止了
}
}

后台线程所派生的子线程都是隐式的后台线程;

另外的线程定义方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SimpleThread extends Thread {
public SimpleThread() {
start();
}
@Override
public void run() {
super.run();
}
public static void main(String []arg)
{
new SimpleThread();
}
}

ps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class SimpleThread extends Thread {
public SimpleThread() {
start();
Thread.currentThread().setName("la"); //此时修改的其实是Main这个线程的名字
}
@Override
public void run() {
Thread.currentThread().setName("la"); //run之后,修改的就是自己的啦;
System.out.println(Thread.currentThread().getName());
super.run();
}
public static void main(String []arg)
{
SimpleThread a= new SimpleThread();
a.setName("hello");
System.out.println(Thread.currentThread().getName());
}
}

join

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Sleep extends Thread {
private int sleep;
public Sleep(String name , int a)
{
super(name);
sleep=a;
start();
}
public void run()
{
try {
sleep(sleep);
} catch (InterruptedException e) {
System.out.println(getName()+"was interrupt"+isInterrupted());
return;
}
System.out.println(getName() + "has weaken");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Join extends Thread {
private Sleep sleep;
public Join(String name ,Sleep sleep)
{
super(name);
this.sleep=sleep;
start();
}
public void run()
{
try {
sleep.join();
} catch (InterruptedException e) {
System.out.println("interrupt");
}
System.out.println(getName() + " complete");
}
public static void main(String []arg)
{
Sleep sleep = new Sleep("sleep",1000);
Sleep grumy = new Sleep("g",1500);
Join d = new Join("do",sleep);
Join p = new Join("po",grumy);
grumy.interrupt();
}
}
output:
gwas interruptfalse
po complete
sleephas weaken
do complete

异常捕捉

主线程无法捕捉线程的异常,只能通过一个中介,在Thread附着一个异常处理器;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
class ExceptionThread2 implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println("eh=" + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
class HandlerThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t + " ID:" + t.getId());
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("eh=" + t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors
.newCachedThreadPool(new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}